#!/bin/bash

if [ $# -lt 1 ]; then
  echo "USAGE: frankensusi <path to gosa-si-server_....deb>"
  echo
  echo "Takes the provided dead body parts..."
  echo "inserts a go-susi brain..."
  echo "stitches the whole thing together and..."
  echo
  echo "           IT'S ALIVE !!!!"
  exit 0
fi

test $UID != 0 && {
  exec fakeroot "$0" "$@"
  echo 2>&1 "Must be run by root or the command fakeroot must be available"
  exit 1
}

dead="$(readlink -f "$1")"

# if CWD is main, go one directory up
test -x ../main/frankensusi && cd ..

make || exit 1

test -x go-susi || {
  echo 2>&1 "Igor! Fetch me a brain!"
  exit 1
}

temp=/tmp/frankensusi.$$.$RANDOM
while ! mkdir "$temp" ; do
  temp=/tmp/frankensusi.$$.$RANDOM
done

trap "rm -rf $temp" EXIT

version="$(./go-susi --version | sed -n 's/^go-susi \([^ ]*\).*/\1/p')"
deb="$(readlink -f .)/go-susi_$version.deb"

rm -f "$deb"

debroot="$temp/go-susi-$version"

mkdir -p "$debroot/DEBIAN" || exit 1

dpkg-deb --control "$dead" "$debroot/DEBIAN" || exit 1
dpkg-deb --extract "$dead" "$debroot"        || exit 1

mkdir "$debroot/usr/lib/go-susi"
chmod u=rwx,go=rx "$debroot/usr/lib/go-susi"
cp ./go-susi "$debroot/usr/lib/go-susi/gosa-si-server"
cp ./sibridge "$debroot/usr/sbin"
ln -snf /usr/lib/go-susi/gosa-si-server "$debroot/usr/sbin/go-susi"
rm "$debroot/usr/sbin/gosa-si-server"
cp main/gosa-si-server "$debroot/usr/sbin"
cp main/generate_{kernel,package}_list "$debroot/usr/lib/go-susi"
chmod u=rwx,go=rx "$debroot/usr/lib/go-susi"/* "$debroot/usr/sbin/"{go-susi,sibridge,gosa-si-server}
sed -i 's%/usr/lib/gosa-si-server%/usr/lib/go-susi/gosa-si-server%g' "$debroot/usr/sbin/gosa-si-server"
rm "$debroot/DEBIAN/md5sums"

sed -r -i -e "
s/^Package:.*/Package: go-susi/
s/^Source:.*/Source: go-susi/
s/^Version:.*/Version: $version/
s/^Maintainer:.*/Maintainer: Susi Frankenstein <mux2005@gmail.com>/
/^Installed-Size:/d
s/^(Depends:.*)/\1, ldap-utils/
/^Depends:/a\
Conflicts: gosa-si-server\n\
Replaces: gosa-si-server
" "$debroot/DEBIAN/control"

chown -R root: "$debroot"
chmod -R a+rX "$debroot"



dpkg-deb -b "$debroot" "$deb"
